package com.weasing.res.utils;

import java.util.ArrayList;
import java.util.List;

import com.weasing.res.domain.WxAdmin;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * jsonUtils 工具类
 * 
 * @author long
 *
 */
public class JsonUtils {


	/**
	 * 对象转json 字符串
	 * 
	 * @author 黄龙
	 */
	public static String Object2Json(Object obj) {
		JSONObject json = JSONObject.fromObject(obj);
		return json.toString();
	}

	/**
	 * 将json转换为bean
	 * 
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> Object Json2Bean(String json, Class<T> type) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		return JSONObject.toBean(jsonObject, type);
	}

	/**
	 * 将json转换为bean
	 * 
	 * @author 黄龙
	 * @param json
	 * @param type
	 * @return
	 */
	public static String BeanstoJsonArray(Object... objs) {
		List<Object> list = new ArrayList<Object>();
		for (Object obj : objs) {
			list.add(obj);
		}
		JSONArray jsonArr = JSONArray.fromObject(list);
		return jsonArr.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args){
		String str = "{" + "\"id\":" + "\"1\"," + "\"name\":" + "\"zhangsan\""
				+ "}";
		// 1.将字符串转为JSON
		JSONObject jsonObj = JSONObject.fromObject(str);
		System.out.println(jsonObj.toString());
		// JSON添加属性
		jsonObj.put("age", "22");
		jsonObj.put("name", "李四");

		System.out.println(jsonObj.toString());
		// 2.将对象转为数组
		JSONArray jsonArr = JSONArray.fromObject(jsonObj);
		System.out.println(jsonArr.toString());
		// 3.将数组添加到JSON对象中
		JSONObject obj = new JSONObject();
		obj.put("employees", jsonArr);
		System.out.println(obj.toString());
		// ------------------------------------------------------------------
		// 4.将对象转化为json
		WxAdmin wxAdmin = new WxAdmin();
		wxAdmin.setId(12121212);
		wxAdmin.setCompname("公司ming");
		wxAdmin.setTruename("黄龙");
		// 1.将对象转为json
		JSONObject json = JSONObject.fromObject(wxAdmin);
		System.out.println(json.toString());

		// JSON转为bean
		WxAdmin json2Bean = (com.weasing.res.domain.WxAdmin) JsonUtils
				.Json2Bean(json.toString(), WxAdmin.class);
		System.out.println(json2Bean.toString());
		System.out.println("---------------");
		
		

	}
}
